package leetcode.offer;

import leetcode.base.ListNode;

public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = getNode(dummy, n + 1);
        prev.next = prev.next.next;
        return dummy.next;
    }

    public ListNode getNode(ListNode head, int n) {
        ListNode fast = head;
        ListNode slow = head;
        for (int i = 0;i < n;i++) {
            fast = fast.next;
        }

        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
